package com.cms.acase.proxy;

import android.content.ComponentName;
import android.content.Intent;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author: Mr.You
 * @create: 2023-11-10 16:30
 * @description:
 **/
public class HookTools {

    public static void hookProxy(){

        try {
            Class<?> aClass = Class.forName("android.app.ActivityTaskManager");
            Field iActivityTaskManagerSingleton = aClass.getDeclaredField("IActivityTaskManagerSingleton");
            iActivityTaskManagerSingleton.setAccessible(true);
            Object mSingleton = iActivityTaskManagerSingleton.get(null);

            Class<?> aClassSingleton = Class.forName("android.util.Singleton");

            Field mInstance = aClassSingleton.getDeclaredField("mInstance");
            mInstance.setAccessible(true);
            Method get = aClassSingleton.getMethod("get");
            Object IActivityTaskManager = get.invoke(mSingleton);

            Class aClassIActivityTaskManager = Class.forName("android.app.IActivityTaskManager");
            Object proxy = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{aClassIActivityTaskManager}, new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    if (method.getName().equals("startActivity")){
                        int mIndex = -1;
                        for (int i = 0; i < args.length; i++) {
                            if (args[i] instanceof Intent){
                                mIndex = i;
                                break;
                            }
                        }
                        Intent intent = (Intent) args[mIndex];
                        Intent newIntent = new Intent();
                        newIntent.setClassName("com.cms.acase.proxy", TargetActivity.class.getName());

                        newIntent.putExtra("abc",intent);
                        args[mIndex] = newIntent;
                    }


                    return method.invoke(IActivityTaskManager,args);
                }
            });
            mInstance.set(mSingleton,proxy);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}
